package org.eclipse.jenkins;

import java.net.URL;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import org.eclipse.jenkins.dom.Hudson;
import org.eclipse.jenkins.dom.View;

public class Client {

	private static final String PACKAGE = Hudson.class.getPackage().getName();
	
	private final URL url;

	private JAXBContext context;

	public Client(URL url) {

		this.url = url;
		try {
			context = JAXBContext.newInstance(PACKAGE);
		} catch (JAXBException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	public List<View> getViews() {

		List<View> result = null;
		
		try {
			
			Unmarshaller u = context.createUnmarshaller();
			
		    @SuppressWarnings("unchecked")
			JAXBElement<Hudson> doc = (JAXBElement<Hudson>)u.unmarshal(url);
			
			Hudson hudson = doc.getValue();
			
			result = hudson.getViews();
			
		} catch (JAXBException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return result;
	}

	public View getPrimaryView() {
		View result = null;
		
		try {
			
			Unmarshaller u = context.createUnmarshaller();
			
		    @SuppressWarnings("unchecked")
			JAXBElement<Hudson> doc = (JAXBElement<Hudson>)u.unmarshal(url);
			
			Hudson hudson = doc.getValue();
			
			result = hudson.getPrimaryView();
			
		} catch (JAXBException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return result;
	}

}
